package il.technion.cs236369.webserver.handlers;

import il.technion.cs236369.webserver.components.IDataHandler;
import il.technion.cs236369.webserver.components.INewWebRequest;
import il.technion.cs236369.webserver.components.WebRequest;
import il.technion.cs236369.webserver.components.QueueHandler;
import il.technion.cs236369.webserver.components.ServerUtils;

import java.net.URI;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.http.HttpRequest;
import org.apache.http.HttpServerConnection;

/**
 * This class handles new Sockets coming from the socket queue.
 * @author Ofir Haviv and Itamar Talmi
 *
 */
public class QueueHttpServerConnectionHandler implements IDataHandler<HttpServerConnection> {

	private BlockingQueue<INewWebRequest> requestsQueue;
	
	/**
	 * The constructor of the QueueHttpServerConnectionHandler class.
	 * @param requestQueueCapacity - The capacity of the requests queue.
	 * @param numberOfRequestReadersThreads - The number of threads to read from the request queue.
	 * @param requestHandler - Handler of the requests coming from the request queue
	 */
	public QueueHttpServerConnectionHandler(int requestQueueCapacity, int numberOfRequestReadersThreads, IDataHandler<INewWebRequest> requestHandler){
		requestsQueue = new LinkedBlockingQueue<INewWebRequest>(requestQueueCapacity);
		new QueueHandler<INewWebRequest>(numberOfRequestReadersThreads, requestsQueue, requestHandler);
	}
	
	@Override
	public void handleData(HttpServerConnection clientConnection) {
		
		INewWebRequest newWebRequest;
		try {

			newWebRequest = new WebRequest(clientConnection.receiveRequestHeader());
			
		} catch (Exception e) {
			ServerUtils.sendInternalServerError(clientConnection);
			e.printStackTrace(); //TODO: Remove when done.
			return;
		}
		
	//	System.out.println("new connection has arrived");
		
		while (true){
			try {
				 // Blocking command (according to the PDF page 7 "Socket-Reader Threads" section).
				requestsQueue.put(newWebRequest);
				break;
			} catch (InterruptedException e) {
				// Tries again
			}
		}
		
	}

}
